<template>
  <a-modal
    v-model:open="visible"
    title="个人信息"
    :footer="null"
    width="600px"
    @cancel="handleCancel"
  >
    <div class="profile-modal-content">
      <!-- 头像部分 -->
      <div class="avatar-section">
        <a-upload
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :custom-request="customUpload"
          accept="image/*"
        >
          <div class="avatar-container">
            <a-avatar :size="100" :src="avatarUrl">
              {{ authStore.user?.displayName?.[0] || authStore.user?.username?.[0] }}
            </a-avatar>
            <div class="avatar-overlay">
              <CameraOutlined />
              <span>更换头像</span>
            </div>
          </div>
        </a-upload>
        <div class="avatar-loading" v-if="isUploadingAvatar">
          <a-spin size="small" />
          <span>上传中...</span>
        </div>
        <p class="avatar-hint">点击头像更换图片</p>
      </div>

      <!-- Tabs 内容 -->
      <a-tabs v-model:activeKey="activeTab" centered>
        <a-tab-pane key="profile" tab="个人信息">
          <div class="tab-content">
            <a-form
              :model="form"
              layout="vertical"
              @finish="handleSubmit"
            >
              <a-form-item label="用户名">
                <a-input v-model:value="form.username" disabled />
              </a-form-item>

              <a-form-item label="邮箱">
                <a-input v-model:value="form.email" disabled />
              </a-form-item>

              <a-form-item
                label="显示名称"
                name="displayName"
                :rules="[{ required: true, message: '请输入显示名称' }]"
              >
                <a-input
                  v-model:value="form.displayName"
                  placeholder="请输入显示名称"
                  :maxlength="50"
                />
              </a-form-item>

              <div class="form-actions">
                <a-space>
                  <a-button @click="handleCancel">取消</a-button>
                  <a-button
                    type="primary"
                    html-type="submit"
                    :loading="isUpdating"
                  >
                    保存
                  </a-button>
                </a-space>
              </div>
            </a-form>
          </div>
        </a-tab-pane>

        <a-tab-pane key="password" tab="修改密码">
          <div class="tab-content">
            <a-form
              :model="passwordForm"
              layout="vertical"
              @finish="handlePasswordChange"
            >
              <a-form-item
                label="当前密码"
                name="currentPassword"
                :rules="[{ required: true, message: '请输入当前密码' }]"
              >
                <a-input-password
                  v-model:value="passwordForm.currentPassword"
                  placeholder="请输入当前密码"
                />
              </a-form-item>

              <a-form-item
                label="新密码"
                name="newPassword"
                :rules="[
                  { required: true, message: '请输入新密码' },
                  { min: 6, message: '密码至少6位' }
                ]"
              >
                <a-input-password
                  v-model:value="passwordForm.newPassword"
                  placeholder="请输入新密码"
                />
              </a-form-item>

              <a-form-item
                label="确认新密码"
                name="confirmPassword"
                :rules="[
                  { required: true, message: '请确认新密码' },
                  { validator: validateConfirmPassword }
                ]"
              >
                <a-input-password
                  v-model:value="passwordForm.confirmPassword"
                  placeholder="请确认新密码"
                />
              </a-form-item>

              <div class="form-actions">
                <a-space>
                  <a-button @click="resetPasswordForm">重置</a-button>
                  <a-button
                    type="primary"
                    html-type="submit"
                    :loading="isChangingPassword"
                  >
                    修改密码
                  </a-button>
                </a-space>
              </div>
            </a-form>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { CameraOutlined } from '@ant-design/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { apiService } from '@/services/api'
import type { UploadResult } from '@/types'

interface Props {
  open: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const authStore = useAuthStore()

const visible = computed({
  get: () => props.open,
  set: (value) => emit('update:open', value)
})

// 表单数据
const form = ref({
  username: '',
  email: '',
  displayName: ''
})

const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 状态
const isUpdating = ref(false)
const isChangingPassword = ref(false)
const isUploadingAvatar = ref(false)
const avatarUrl = ref<string>('')
const activeTab = ref('profile')

// 初始化表单数据
const initForm = () => {
  if (authStore.user) {
    form.value = {
      username: authStore.user.username,
      email: authStore.user.email,
      displayName: authStore.user.displayName || ''
    }
    avatarUrl.value = authStore.user.avatar || ''
  }
}

// 监听模态框打开状态
watch(() => props.open, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 上传前验证
const beforeUpload = (file: File) => {
  console.log('beforeUpload called with file:', file)

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    message.error('请选择图片文件')
    return false
  }

  // 验证文件大小 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    message.error('图片大小不能超过 5MB')
    return false
  }

  return true
}

// 自定义上传
const customUpload = async (options: any) => {
  console.log('customUpload called with options:', options)
  const { file } = options

  try {
    isUploadingAvatar.value = true
    const result: UploadResult = await apiService.uploadAvatar(file)

    // 更新头像URL - 静态文件不需要/api前缀
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5276/api'
    const staticBaseUrl = baseUrl.replace('/api', '')
    const fullAvatarUrl = `${staticBaseUrl}${result.url}`
    avatarUrl.value = fullAvatarUrl

    // 更新用户信息
    await authStore.updateUser({ avatar: fullAvatarUrl })

    message.success('头像上传成功')
    options.onSuccess(result)
  } catch (error: any) {
    console.error('Upload error:', error)
    message.error(error.response?.data?.message || '头像上传失败')
    options.onError(error)
  } finally {
    isUploadingAvatar.value = false
  }
}

// 提交个人信息
const handleSubmit = async () => {
  try {
    isUpdating.value = true
    // 只更新显示名称，保留现有头像
    await authStore.updateUser({
      displayName: form.value.displayName,
      avatar: authStore.user?.avatar // 保留现有头像
    })
    message.success('个人信息更新成功')
  } catch (error: any) {
    message.error(error.response?.data?.message || '更新失败')
  } finally {
    isUpdating.value = false
  }
}

// 修改密码
const handlePasswordChange = async () => {
  try {
    isChangingPassword.value = true
    await authStore.changePassword(
      passwordForm.value.currentPassword,
      passwordForm.value.newPassword
    )
    message.success('密码修改成功')
    
    // 清空密码表单
    passwordForm.value = {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error: any) {
    message.error(error.response?.data?.message || '密码修改失败')
  } finally {
    isChangingPassword.value = false
  }
}

// 验证确认密码
const validateConfirmPassword = (_rule: any, value: string) => {
  if (value && value !== passwordForm.value.newPassword) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.value = {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

// 取消操作
const handleCancel = () => {
  visible.value = false
  activeTab.value = 'profile'
  resetPasswordForm()
}
</script>

<style scoped>
.profile-modal-content {
  padding: 20px 0;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
}

.avatar-container {
  position: relative;
  cursor: pointer;
  margin-bottom: 8px;
  transition: transform 0.2s;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 12px;
  pointer-events: none;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay span {
  margin-top: 4px;
  font-size: 12px;
}

.avatar-hint {
  margin: 8px 0 0 0;
  color: #666;
  font-size: 12px;
  text-align: center;
}

.avatar-loading {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.tab-content {
  padding: 16px 0;
  min-height: 300px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

/* Tabs 样式优化 */
:deep(.ant-tabs-nav) {
  margin-bottom: 0;
}

:deep(.ant-tabs-content-holder) {
  padding-top: 16px;
}

:deep(.ant-tabs-tab) {
  padding: 12px 24px;
}
</style>
